#pragma once 

#include <Renderable.hpp>

class TText2D : public TRenderable
{
	IDKClass;
private:
	Math::Rect mRect;
	String mText;
public:
	TText2D(IDK::Core core, String text, const Math::Rect& rect = Math::Rect::Identity) 
		: mRect(rect), mText(text)
	{
		ref<IDK::IMaterial> mtrl = core->GetMaterial("Font_mtrl");
		mtrl->SetBlendMode(IDK::IRenderState::Blend::AlphaBlend);

		ref<IDK::IShader> shader = core->GetShader("Font");

		shader->AddParameter(IDK::IShaderParameter::Type::VertexAttribute, IDK::IShaderParameter::Declaration::VertexPosition, "Vertex"); 
		shader->AddParameter(IDK::IShaderParameter::Type::ConstantParameter, IDK::IShaderParameter::Declaration::Texture0, "Sampler0"); 

		IDK::Texture texture = core->AddTexture("Font/decal", IDK::Pixel::Type::RGBA4, 1, 512, 512);

		mtrl->SetTexture(IDK::IMaterial::TextureMode::Sampler0, texture);
		mtrl->SetShader(shader);

		SetMaterial(mtrl);
	}

	void SetText(String text)
	{
		mText = text;
	}

	virtual bool Render(IDK::IRenderState& rndState)
	{
		rndState.SetBlend(IDK::IRenderState::Blend::AlphaBlend);

		bool result = TRenderable::Render(rndState);

		const uint glyphLineCount = 16;

		uint start = ' ';

		Math::Rect slideRect = mRect; //copy for edit

		float size = slideRect.right - slideRect.left;

		for(String::Iterator it = mText->Begin(), end = mText->End(); it!=end; ++it)
		{
			uint glyph = *it - start;

			uint glyphPosX = (glyph % glyphLineCount);
			uint glyphPosY = (glyph / glyphLineCount);

			float glyphSize = 1.0f / 16.0f;

			float glyphX = glyphSize * glyphPosX;
			float glyphY = glyphSize * glyphPosY;

			rndState.DrawRect(slideRect, Math::Rect(glyphX, glyphY, glyphX+glyphSize, glyphY+glyphSize));

			//new position
			slideRect.left += size / 2.0f;
			slideRect.right += size / 2.0f;
		}
		return result;
	}
};

typedef ref<TText2D> Text2D;